package cc.rengu.igas.bomp.core.service.trans;

import cc.rengu.igas.bomp.common.constant.DubboMethodConstant;
import cc.rengu.igas.bomp.common.dao.AuthUserMapper;
import cc.rengu.igas.bomp.common.dao.ManagerInfoMapper;
import cc.rengu.igas.bomp.common.dao.MchntBaseInfoMapper;
import cc.rengu.igas.bomp.common.dao.OnlineVerificationMapper;
import cc.rengu.igas.bomp.common.dao.impl.AuthUserMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.ManagerInfoMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.MchntBaseInfoMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.OnlineVerificationMapperImpl;
import cc.rengu.igas.bomp.common.entity.AuthUser;
import cc.rengu.igas.bomp.common.entity.ManagerInfo;
import cc.rengu.igas.bomp.common.entity.MchntBaseInfo;
import cc.rengu.igas.bomp.common.entity.OnlineVerification;
import cc.rengu.igas.bomp.common.enums.RespCodeEnum;
import cc.rengu.igas.bomp.common.util.InitParamUtil;
import cc.rengu.igas.bomp.core.service.base.ManageService;
import cc.rengu.igas.bomp.facade.request.OnlineVerificationRequest;
import cc.rengu.igas.bomp.facade.response.OnlineVerificationResponse;
import cc.rengu.igas.share.common.util.GlobalEsbUtil;
import cc.rengu.igas.smps.facade.base.Header;
import cc.rengu.igas.smps.facade.request.IdentityNetworkVerifyRequest;
import cc.rengu.igas.smps.facade.response.IdentityNetworkVerifyResponse;
import cc.rengu.igas.smps.facade.result.Result;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.DateUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;

import java.util.UUID;

/**
 * @author zhangxuran
 * @version 1.0
 * date 2020/4/8 14:08
 * 功能描述： 联网核查
 * update by zhangxuran on 2020.05.21自测调整
 */
public class OnlineVerificationService extends ManageService {

    @Override
    protected Object bizBeforeCust() throws Exception {
        OnlineVerificationRequest onlineVerificationRequest = new OnlineVerificationRequest();
        ConvertUtil.convertOutput(onlineVerificationRequest);
        return onlineVerificationRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        OnlineVerificationRequest onlineVerificationRequest = (OnlineVerificationRequest) request;
        BizResponse<OnlineVerificationResponse> bizResponse = new BizResponse<>();
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);

        OnlineVerificationResponse onlineVerificationResponse = new OnlineVerificationResponse();
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();

        /*获取系统流水号*/
        String sysSeqNum = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM);
        /*获取法人行号*/
        String instId = onlineVerificationRequest.getHeader().getInstId();
        /*获取商户号*/
        String mchntNo = onlineVerificationRequest.getMchntNo();
        /*获取法人证件号码*/
        String certNo = onlineVerificationRequest.getCertNo();
        /*获取法人姓名*/
        String artifName = onlineVerificationRequest.getArtifName();
        /*获取用户Id*/
        String userId = onlineVerificationRequest.getUserId();
        /*获取渠道ID*/
        String channelId = onlineVerificationRequest.getHeader().getChanlId();
        /*必填性校验*/
        if (StringUtil.isEmptyOrNull(instId) || StringUtil.isEmptyOrNull(mchntNo) || StringUtil.isEmptyOrNull(certNo)
                || StringUtil.isEmptyOrNull(artifName) || StringUtil.isEmptyOrNull(userId) || StringUtil.isEmptyOrNull(channelId)) {
            rglog.error("必填性校验失败");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }
        MchntBaseInfoMapper mchntBaseInfoMapper = new MchntBaseInfoMapperImpl();
        MchntBaseInfo mchntBaseInfo = mchntBaseInfoMapper.selectMchntBaseInfoByPrimaryKey(instId, mchntNo);
        if (null == mchntBaseInfo) {
            rglog.error("商户基础信息查询失败！instId:<{}>,mchntNo:<{}>",
                    onlineVerificationRequest.getHeader().getInstId(), onlineVerificationRequest.getMchntNo());
            throw new BizException(RespCodeEnum.QUERY_BASEDATA_IS_NULL.getRespCode(), RespCodeEnum.QUERY_BASEDATA_IS_NULL.getRespDesc());
        }
        ManagerInfoMapper managerInfoMapper = new ManagerInfoMapperImpl();
        String orgCode = "";
        String oprId = "";
        /*根据用户id查询当前用户信息*/
        if (!"MCMP".equals(channelId)) {
            /*商户服务操作查询认证*/
            ManagerInfo managerInfo = null;
            if ("APP".equals(channelId)){
                managerInfo = managerInfoMapper.selectManagerInfoById(instId,userId);
            }else {
                managerInfo = managerInfoMapper.selectManagerInfoByOpenId(instId, onlineVerificationRequest.getUserId());
            }
            if (null == managerInfo) {
                rglog.error("拓展经理信息不存在");
                throw new BizException(RespCodeEnum.QUERY_MANAGER_INFO_ERROR.getRespCode(), RespCodeEnum.QUERY_MANAGER_INFO_ERROR.getRespDesc());
            }
            orgCode = managerInfo.getSignInstId();
            oprId = managerInfo.getManagerId();
        } else {
            /*运营管理操作查询用户信息*/
            AuthUserMapper authUserMapper = new AuthUserMapperImpl();
            AuthUser authUser = authUserMapper.selectAuthUserById(userId);
            if (null == authUser) {
                rglog.error("用户不存在");
                throw new BizException(RespCodeEnum.QUERY_AUTH_USER_IS_NULL.getRespCode(), RespCodeEnum.QUERY_AUTH_USER_IS_NULL.getRespDesc());
            }

            orgCode = authUser.getOrgCode();
            oprId = authUser.getEmpNo();
        }

        /* todo 演示环境默认返回成功 */
        if (AppParamConstant.DEFAULT_ENV.equals(AppParamConstant.APPLICATION_ENV)) {
            onlineVerificationResponse.setCheckResult("Y");
            onlineVerificationResponse.setCertIssueCode("12345");
            onlineVerificationResponse.setCertNo(onlineVerificationRequest.getCertNo());
            onlineVerificationResponse.setName(onlineVerificationRequest.getArtifName());
            onlineVerificationResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
            onlineVerificationResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());

            bizResponse.setRespCode(onlineVerificationResponse.getRespCode());
            bizResponse.setRespDesc(onlineVerificationResponse.getRespDesc());
            bizResponse.setResult(onlineVerificationResponse);
            return bizResponse;
        }

        /*调用dubbo服务*/
        IdentityNetworkVerifyRequest picpRequest = new IdentityNetworkVerifyRequest();
        picpRequest.setCertNo(onlineVerificationRequest.getCertNo());
        picpRequest.setCustomerName(onlineVerificationRequest.getArtifName());
        Header queryHeader = new Header();
        queryHeader.setInstId(instId);
        queryHeader.setChanlId(ChannelEnum.BOMP.getChannelType());
        queryHeader.setSrcSysId(AppParamConstant.SYS_ID);
        queryHeader.setTxnNum("00660000000000");
        queryHeader.setTransDate(DateUtil.getCurrentDate());
        queryHeader.setTransTime(DateUtil.getCurrentTime());
        queryHeader.setTraceNo(GlobalEsbUtil.generateEsbSeqeuenceNumber(instId));
        picpRequest.setHeader(queryHeader);

        DubboService dubboService = new DubboServiceImpl();
        Result<IdentityNetworkVerifyResponse> picpResult = (Result<IdentityNetworkVerifyResponse>) dubboService.callDubboService(DubboMethodConstant.DUBBO_RISK_ALARM_SERVICE, "identityNetworkVerify", picpRequest);
        if (null == picpResult || !picpResult.isSuccess()
                || !DubboMethodConstant.DUBBO_SUCCESS.equals(picpResult.getResult().getRespCode())) {
            onlineVerificationResponse.setRespCode(null == picpResult ? RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespCode() : picpResult.getResult().getRespCode());
            onlineVerificationResponse.setRespDesc(null == picpResult ? RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc() : picpResult.getResult().getRespDesc());
            bizResponse.setResult(onlineVerificationResponse);
        } else {
            //核查完成时间
            onlineVerificationResponse.setCheckResult(picpResult.getResult().getVerifyResult());
            onlineVerificationResponse.setCertIssueCode(picpResult.getResult().getIssueAgency());
            onlineVerificationResponse.setCertNo(picpResult.getResult().getCertNo());
            onlineVerificationResponse.setName(picpResult.getResult().getCustomerName());
            onlineVerificationResponse.setCheckCertImage(picpResult.getResult().getPhoto());
            onlineVerificationResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
            onlineVerificationResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        }

        /*拓展经理所在机构赋值*/
        onlineVerificationRequest.getHeader().setRemark(orgCode);
        /*插入联网核查查询记录*/
        insertOnlineVerificationInfo(onlineVerificationRequest, sysSeqNum, mchntBaseInfo, picpResult.getResult(), orgCode, oprId);
        bizResponse.setRespCode(onlineVerificationResponse.getRespCode());
        bizResponse.setRespDesc(onlineVerificationResponse.getRespDesc());
        bizResponse.setResult(onlineVerificationResponse);
        return bizResponse;
    }

    /**
     * 联网核查记录方法
     */
    private void insertOnlineVerificationInfo(OnlineVerificationRequest onlineVerificationRequest,
                                              String sysSeqNum, MchntBaseInfo mchntBaseInfo,
                                              IdentityNetworkVerifyResponse picpResponse,
                                              String orgCode, String oprId) throws Exception {
        OnlineVerification onlineVerification = new OnlineVerification();
        String id = UUID.randomUUID().toString().replaceAll("-", "");
        onlineVerification.setId(id);
        onlineVerification.setInstId(onlineVerificationRequest.getHeader().getInstId());
        onlineVerification.setMchntName(mchntBaseInfo.getMchntName());
        onlineVerification.setMchntNo(mchntBaseInfo.getMchntNo());
        onlineVerification.setCheckInst(onlineVerificationRequest.getHeader().getRemark());
        onlineVerification.setCheckPerson(oprId);
        onlineVerification.setSysSeqNum(sysSeqNum);
        onlineVerification.setArtifName(onlineVerificationRequest.getArtifName());
        onlineVerification.setArtifIdNo(onlineVerificationRequest.getCertNo());
        if (StringUtil.isEmptyOrNull(picpResponse.getVerifyResult())) {
            //其他错误
            onlineVerification.setCheckStatus("04");
        } else {
            onlineVerification.setCheckStatus(picpResponse.getVerifyResult());
        }
        onlineVerification.setCheckResult(picpResponse.getRespDesc());
        onlineVerification.setOprId(onlineVerificationRequest.getUserId());
        onlineVerification.setCrtOrgId(orgCode);
        onlineVerification.setCheckTime(DateUtil.getCurrentDateTime(InitParamUtil.yyyy_MM_dd_HHmmssSSS));
        onlineVerification.setCreateTime(DateUtil.getCurrentDateTime(InitParamUtil.yyyy_MM_dd_HHmmssSSS));
        onlineVerification.setRemark1(picpResponse.getRespCode());
        onlineVerification.setRemark2(picpResponse.getRespDesc());

        OnlineVerificationMapper onlineVerificationMapper = new OnlineVerificationMapperImpl();
        int dbResult = onlineVerificationMapper.insertOnlineVerification(onlineVerification);
        if (dbResult != 0) {
            rglog.error("登记商户联网核查记录查询表失败！");
            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
        }
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        OnlineVerificationResponse onlineVerificationResponse = (OnlineVerificationResponse) bizResponse.getResult();
        ConvertUtil.convertInput(onlineVerificationResponse);
    }
}
